package terra.model;

import java.io.Serializable;

import terra.Config;
import terra.managers.MapManager;
import terra.model.map.Map;
import terra.model.object.GObject;
import terra.model.object.interfaces.ChangeListener;
import terra.model.object.map.AbstractMapObject;
import terra.model.object.map.GroundObject;
import terra.model.object.map.MapObject;

public class GroundListener implements ChangeListener, Serializable {
	private static final long serialVersionUID = 8375134570293613091L;

	@Override
	public void objectChanged(GObject object) {
		if (object instanceof GroundObject)
			checkGround((AbstractMapObject) object);
	}

	public void checkGround(AbstractMapObject obj) {
		int mapIndex = obj.getMap().index;
		int x = obj.getTileX();
		obj.removeListener(this);
		checkGround(mapIndex, x);
	}

	public void checkGround(int mapIndex, int x) {
		Map map = MapManager.instance.getMaps().get(mapIndex);
		if (map == null)
			return;
		if (map.getGroundLine()[x] < Config.mapHeight)
			if (map.getMap()[x][map.getGroundLine()[x]] != null)
				map.getMap()[x][map.getGroundLine()[x]].removeListener(this);

		AbstractMapObject obj;
		if (map.getGroundLine()[x] < Config.mapHeight)
			obj = map.getMap()[x][map.getGroundLine()[x]];
		else
			obj = map.getMap()[x][Config.mapHeight - 1];
		int y = 0;
		AbstractMapObject air = map.getMap()[x][y];
		while (air == null || air.canMove())
			air = map.getMap()[x][y++];
		// while(air.getNeighbor(MapObject.DOWN).getType() != 1 ||
		// air.getNeighbor(MapObject.DOWN).handMaded)
		// FIXME while(air.getNeighbor(MapObject.DOWN).canMove() ||
		// air.getNeighbor(MapObject.DOWN).handMaded)
		// while(air.getNeighbor(MapObject.DOWN).canMove())
		// air = air.getNeighbor(MapObject.DOWN);
		if (air != obj){
			if (air.getNeighbor(MapObject.DOWN) != null)
				map.getGroundLine()[x] = air.getNeighbor(MapObject.DOWN).getTileY();
		}

		map.getMap()[x][map.getGroundLine()[x]].addListener(this);
	}

	public void addListeners(int index) {
		Map m = MapManager.instance.getMaps().get(index);
		for (int x = 0; x < Config.mapWidth; x++)
			if (m.getMap()[x][m.getGroundLine()[x]] != null)
				m.getMap()[x][m.getGroundLine()[x]].addListener(this);
	}

	public void checkNewGround(AbstractMapObject obj) {
		if (obj.getTileY() >= obj.getMap().getGroundLine()[obj.getTileX()])
			checkGround(obj);
	}

}
